﻿Imports System.Timers
Imports System.Configuration
Imports QueueManager.Service.Config
Imports QueueManager.Helper

Public Class QueueService

    Private WithEvents _objTimer As New Timer
    Private _objSettings As QueueSection
    Private _objMonitor As New QueueMonitor
    Private _objLastTempQueueRun As DateTime = DateTime.MinValue
    Private _objLastRun As New Collections.Generic.Dictionary(Of String, DateTime)

    Protected Overrides Sub OnStart(ByVal args() As String)

        LogHelper.Log(String.Format("CRM Queue Manager {0} started.", My.Application.Info.Version.ToString(4)), Nothing, LogHelper.LogType.Information)

        _objTimer.Start()

    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub

    Public Sub New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        _objSettings = CType(ConfigurationManager.GetSection("queues"), QueueSection)

        'Set timer 10 to fire off every 10 seconds
        _objTimer.Interval = 10000
        _objTimer.AutoReset = False
        _objTimer.Start()

    End Sub

    Private Sub _objTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _objTimer.Elapsed

        _objTimer.Stop()

        For Each objQueue As QueueSetting In _objSettings.Queues
            If _objLastRun.ContainsKey(objQueue.Name) Then
                If Now.Subtract(_objLastRun(objQueue.Name)).TotalSeconds > objQueue.Interval Then
                    _objMonitor.ProcessQueue(objQueue)
                    _objLastRun.Item(objQueue.Name) = Now
                End If
            Else
                _objMonitor.ProcessQueue(objQueue)
                _objLastRun.Add(objQueue.Name, Now)
            End If
        Next

        'Should we process temp queues?
        If Now.Subtract(_objLastTempQueueRun).TotalHours > 1 Then
            For Each objQueue As QueueSetting In _objSettings.Queues
                _objMonitor.ProcessTempQueue(objQueue)
            Next

            _objLastTempQueueRun = Now
        End If

        _objTimer.Start()

    End Sub
End Class
